/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.alvin.switchserver.ui;

import org.alvin.mini_inject.annotations.MiniComponent;
import org.alvin.mini_inject.annotations.MiniRun;
import org.alvin.switchserver.MultiServerForwarding;
import org.alvin.switchserver.ServerNode;
import org.alvin.switchserver.ui.models.ServerNodeTableModel;
import org.alvin.switchserver.utils.NetworkUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

/**
 * @author 86139
 */

@MiniComponent
public class SwitchTcpFrame extends javax.swing.JFrame {

    private ServerNodeTableModel serverNodeTableModel = new ServerNodeTableModel();
    private MultiServerForwarding multiServerForwarding;

    private PropertyChangeSupport frameUiEventBus = new PropertyChangeSupport("");


    @MiniRun
    public void startUI() {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SwitchTcpFrame.this.setVisible(true);
            }
        });
    }

    /**
     * Creates new form SwitchTcpFrame
     */
    public SwitchTcpFrame() {
        initComponents();
        this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
        this.setSize(1440, 768);
        this.txtServerIp.setText(NetworkUtils.getRealIP());
        this.txtPort.setText("8090");
        this.tblForwardServer.setModel(serverNodeTableModel);

        frameUiEventBus.addPropertyChangeListener("serverStatusChange", new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                lblServerStatus.setText(evt.getNewValue().toString());
                serverNodeTableModel.setServerStatus(evt.getNewValue().toString());
            }
        });

        frameUiEventBus.addPropertyChangeListener("inputNettyMessage", new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                txtSendData.append("发送数据：");
                txtSendData.append(evt.getNewValue().toString());
                txtSendData.append("\n");
                //
                String text = txtSendData.getText();
//                if(text.length() >= 5000){
//                    text = text.substring(text.length() - 3000 );
//                }
                txtSendData.setText(text);
            }
        });

        frameUiEventBus.addPropertyChangeListener("outputNettyMessage", new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                txtReceive.append("收到数据：");
                txtReceive.append(evt.getNewValue().toString());
                txtReceive.append("\n");
                //
                String text = txtReceive.getText();
//                if(text.length() >= 5000){
//                    text = text.substring(text.length() - 3000 );
//                }
                txtReceive.setText(text);
            }
        });

        btnStartServer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (txtServerIp.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(SwitchTcpFrame.this, "请输入服务器IP");
                    return;
                }
                if (txtPort.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(SwitchTcpFrame.this, "请输入服务器端口");
                    return;
                }
                if (serverNodeTableModel.getDataList().isEmpty()) {
                    JOptionPane.showMessageDialog(SwitchTcpFrame.this, "请至少有一个代理服务");
                    return;
                }
                if(serverNodeTableModel.getDataList().stream().filter(item-> item.isDefault()).count() != 1){
                    JOptionPane.showMessageDialog(SwitchTcpFrame.this, "只能有有个主服务");
                    return;
                }
                txtReceive.setText("");
                txtSendData.setText("");
                //启动服务
                multiServerForwarding = new MultiServerForwarding(Integer.parseInt(txtPort.getText().trim()), serverNodeTableModel, frameUiEventBus);
                multiServerForwarding.start();

            }
        });

        btnStopServer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (multiServerForwarding != null) {
                    multiServerForwarding.stop();
                }
            }
        });

        btnAddForwordServer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (multiServerForwarding != null && multiServerForwarding.isOpen()) {
                    JOptionPane.showMessageDialog(SwitchTcpFrame.this, "服务已开，不要添加");
                    return;
                }

                serverNodeTableModel.addRow();
            }
        });

        btnDelForwardServer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (multiServerForwarding != null && multiServerForwarding.isOpen()) {
                    JOptionPane.showMessageDialog(SwitchTcpFrame.this, "服务已开，不要删除");
                    return;
                }
                if(tblForwardServer.getSelectedRow() == -1){
                    JOptionPane.showMessageDialog(SwitchTcpFrame.this, "请选择要删除的行");
                    return ;
                }
                int row = tblForwardServer.convertRowIndexToModel(tblForwardServer.getSelectedRow());
                serverNodeTableModel.delRow(row);
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtServerIp = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtPort = new javax.swing.JTextField();
        btnStartServer = new javax.swing.JButton();
        btnStopServer = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        lblServerStatus = new javax.swing.JLabel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        btnAddForwordServer = new javax.swing.JButton();
        btnDelForwardServer = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblForwardServer = new javax.swing.JTable();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtSendData = new javax.swing.JTextArea();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtReceive = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("超哥哥专用-请认准超哥哥品牌-协议1转多份-V1.0");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("服务配置"));

        jLabel1.setText("服务器IP:");

        jLabel2.setText("端口：");

        btnStartServer.setText("启动服务");

        btnStopServer.setText("停止服务");

        jLabel3.setText("服务状态：");

        lblServerStatus.setText("Stopped");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(21, 21, 21)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(jLabel3)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(lblServerStatus))
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(jLabel1)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(txtServerIp, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addComponent(jLabel2)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addComponent(btnStartServer)
                                                .addGap(18, 18, 18)
                                                .addComponent(btnStopServer)))
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[]{txtPort, txtServerIp});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[]{jLabel1, jLabel3});

        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(15, 15, 15)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel1)
                                        .addComponent(txtServerIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel2)
                                        .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btnStartServer)
                                        .addComponent(btnStopServer))
                                .addGap(18, 18, 18)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(jLabel3)
                                        .addComponent(lblServerStatus))
                                .addContainerGap(16, Short.MAX_VALUE))
        );

        btnAddForwordServer.setText("添加转发服务");

        btnDelForwardServer.setText("删除转发服务");

        tblForwardServer.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                        {},
                        {},
                        {},
                        {}
                },
                new String[]{

                }
        ));
        jScrollPane1.setViewportView(tblForwardServer);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 379, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(jPanel2Layout.createSequentialGroup()
                                                .addComponent(btnAddForwordServer)
                                                .addGap(18, 18, 18)
                                                .addComponent(btnDelForwardServer)))
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel2Layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btnAddForwordServer)
                                        .addComponent(btnDelForwardServer))
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE)
                                .addContainerGap())
        );

        jTabbedPane1.addTab("转发服务列表", jPanel2);

        jPanel3.setLayout(new java.awt.BorderLayout());

        txtSendData.setEditable(false);
        txtSendData.setColumns(20);
        txtSendData.setLineWrap(true);
        txtSendData.setRows(5);
        jScrollPane2.setViewportView(txtSendData);

        jPanel3.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jTabbedPane2.addTab("发送数据", jPanel3);

        jPanel4.setLayout(new java.awt.BorderLayout());

        txtReceive.setEditable(false);
        txtReceive.setColumns(20);
        txtReceive.setLineWrap(true);
        txtReceive.setRows(5);
        jScrollPane3.setViewportView(txtReceive);

        jPanel4.add(jScrollPane3, java.awt.BorderLayout.CENTER);

        jTabbedPane2.addTab("接收主服务数据", jPanel4);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(18, 18, 18)
                                                .addComponent(jTabbedPane2))
                                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jTabbedPane1)
                                        .addComponent(jTabbedPane2))
                                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddForwordServer;
    private javax.swing.JButton btnDelForwardServer;
    private javax.swing.JButton btnStartServer;
    private javax.swing.JButton btnStopServer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel lblServerStatus;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JTable tblForwardServer;
    private javax.swing.JTextField txtPort;
    private javax.swing.JTextArea txtReceive;
    private javax.swing.JTextArea txtSendData;
    private javax.swing.JTextField txtServerIp;
    // End of variables declaration//GEN-END:variables
}
